#include "trie.h"

using namespace std;

Trie::Trie()
{
    root = new TrieNode();
}

Trie::~Trie()
{
}

void Trie::addWord(string word)
{
    TrieNode* current = root;

    if ( word.length() == 0 )
    {
        current->setFinalWord(); // an empty word
        return;
    }

    for (unsigned int i = 0; i < word.length(); i++ )
    {        
        TrieNode* child = current->findChild(word[i]);
        if ( child != NULL )
        {
            current = child;
        }
        else
        {
            TrieNode* tmp = new TrieNode();
            tmp->setData(word[i]);
            current->appendChild(tmp);
            current = tmp;
        }
        if ( i == word.length() - 1 )
            current->setFinalWord();
    }
}


bool Trie::searchWord(string word)
{
    TrieNode* current = root;

    while ( current != NULL )
    {
        for (unsigned int i = 0; i < word.length(); i++ )
        {
            TrieNode* tmp = current->findChild(word[i]);
            if ( tmp == NULL )
                return false;
            current = tmp;
        }

        if ( current->isFinalWord() )
            return true;
        else
            return false;
    }

    return false;
}